package day13;

import java.io.*;
import java.util.Scanner;

/**
 * @author Xiao
 * @date 2021/8/4
 */
public class Test02 {
    /**
     * 2. 键盘录入数据源路径和目的地路径，分别使用【普通字符流】和【字符缓冲流的特殊功能】完成对指定文件的复制
     *     例如：
     *         数据源： d:\a.txt
     *         目的地： d:\b.txt
     *
     *         就将a.txt文件的数据复制到b.txt中
     */
    public static void main(String[] args) throws IOException {
        //String path1 = "homework\\src\\day13\\a.txt";
        //String path2 = "homework\\src\\day13\\b.txt";
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入源文件路径");
            String path1 = getPath(sc);
            System.out.println("请输入目的地文件路径");
            String path2 = getPath(sc);
            if (!path1.equals(path2)) {
                //普通字符流拷贝文件
                //charStream(path1, path2);
                //字符缓冲流拷贝文件
                bufferedStream(path1, path2);
                return;
            }
            System.out.println("源文件和目的地文件路径相同，请重新输入。");
        }
    }

    private static String getPath(Scanner sc) {
        while (true) {
            String path = sc.nextLine();
            File file = new File(path);
            if (file.exists()) {
                if (file.isFile()) {
                    return path;
                } else {
                    System.out.println("您输入的路径不是文件，请重新输入：");
                    continue;
                }
            }
            System.out.println("您输入的路径不存在，请重新输入：");
        }
    }

    private static void bufferedStream(String path1, String path2) throws IOException{
        BufferedReader br = new BufferedReader(new FileReader(path1));
        BufferedWriter bw = new BufferedWriter(new FileWriter(path2));
        String s;
        while ((s = br.readLine()) != null) {
            bw.write(s);
            bw.newLine();
            bw.flush();
        }
        br.close();
        bw.close();
    }

    private static void charStream(String path1, String path2) throws IOException {
        FileReader fr = new FileReader(path1);
        FileWriter fw = new FileWriter(path2);
        char[] chars = new char[1024];
        int len;
        while ((len = fr.read(chars)) != -1) {
            fw.write(chars,0,len);
        }
        fw.flush();
        fr.close();
        fw.close();
    }
}
